package com.lg.fileservice.controller;

import com.lg.fileservice.model.StorageBo;
import com.lg.fileservice.storage.ObjectStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @Description
 * @Date 2022/6/26 19:00
 * @Created by mike
 */
@RestController
public class FileController {

    @Autowired
    private ObjectStorageService objectStorageService;

    @PostMapping("/uploadFile")
    public String uploadFile(MultipartFile file,String bucketName) {
        try {
            StorageBo storageBo = new StorageBo.Builder().setObjectName(file.getOriginalFilename()).setBucketName(bucketName).setContent(file.getBytes()).build();
            objectStorageService.uploadObjectByBytes(storageBo);
            return "上传文件成功";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传文件失败";
    }

    /**
     * 根据文件名下载文件
     */
    @PostMapping("/downLoad")
    public void uploadFile(String objectName , String bucketName,HttpServletResponse response) {
        BufferedInputStream bis = null;
        try {
            StorageBo storageBo = new StorageBo.Builder().setObjectName(objectName).setBucketName(bucketName).build();
            bis = new BufferedInputStream(objectStorageService.downloadByObjectName(storageBo));
            OutputStream os = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 根据 objectName 删除
     */
    @PostMapping("/deleteFile")
    public String deleteFile(String objectName ,String bucketName) {
        try {
            StorageBo storageBo = new StorageBo.Builder().setObjectName(objectName).setBucketName(bucketName).build();
            objectStorageService.deleteFileByObjectName(storageBo);
            return "删除文件成功";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "删除文件失败";
    }

}
